import os
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
import json

os.environ['HTTP_PROXY'] = 'http://127.0.0.1:10809'
os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:10809'

# 替换为你的OAuth 2.0客户端ID文件路径
CLIENT_SECRETS_FILE = "C:/Users/X/Desktop/字幕/code/client.json" 

# 替换为你的OAuth 2.0授权范围
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']

API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

def get_authenticated_service():
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    credentials = flow.run_local_server()
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

def upload_subtitles(youtube, video_id, language, subtitle_file):
    try:
        request = youtube.captions().insert(
            part="snippet",
            body={
                "snippet": {
                    "language": language,
                    "name": f"",
                    "videoId": video_id
                }
            },
            media_body=MediaFileUpload(subtitle_file)
        )
        response = request.execute()
        print(f"上传完成 {subtitle_file}: {response}")
        
    except HttpError as e:
        print(f"上传失败 {subtitle_file} 错误信息: {e}")
        
def main():
    youtube = get_authenticated_service()
    subtitle_dir = "C:/Users/X/Desktop/字幕/srt"
    with open('C:/Users/X/Desktop/字幕/titles.json', 'r', encoding='utf-8') as file:
        config = json.load(file)
        new_titles = config['titles']
        video_id = config['videoID']
    
        for root, dirs, files in os.walk(subtitle_dir):
            for filename in files:
                if filename.endswith((".srt", ".vtt")):
                    language = filename[:2] # 假设字幕文件名以语言代码开头
                    subtitle_file = os.path.join(root, filename)
                    upload_subtitles(youtube, video_id, language, subtitle_file)

if __name__ == "__main__":
    main()
    os.system("pause")
